# -*- coding : utf-8 -*-
import os

import sys
import json
import datetime

sys.path.append('../../')
from flask import Flask, render_template, request, Response, make_response, stream_with_context
from flask_cors import CORS

from bot.insurance_planner_gpt.tele_wechat_assistant import TeleWechatAssistant
# import config
import asyncio

session_id_dict = dict()

os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"

arg = sys.argv
app = Flask(__name__)
CORS(app, resources=r'/*')
app.static_folder = 'static'


@app.route('/')
def index():
    return render_template('index.html')


@app.route('/init')
def init():
    user_id = request.args.get('userId')
    init_scene = request.args.get('initScene')

    return '请在用户回复中输入"开始"，用户信息中输入用户信息。开始对话'


@app.route('/message')
def message():
    message = request.args.get('message')
    user_id = request.args.get('userId')
    user_info = request.args.get('userInfo')

    print(message)
    print(user_id)
    print(user_info)
    print(type(user_info))
    user_info = eval(user_info)

    # 判定最终需要使用的session Id
    if 'session_id' in user_info:
        session_id = user_info['session_id']
        user_id = session_id

    if user_id not in session_id_dict:
        session_id_dict[user_id] = list()
    if message != '开始':
        conversation_dict = {}
        conversation_dict["role"] = "user"
        conversation_dict["content"] = message
        query_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        conversation_dict["query_time"] = query_time
        session_id_dict[user_id].append(conversation_dict)

    sales = TeleWechatAssistant()
    reply_result = asyncio.run(sales.async_reply_text(session_id_dict[user_id], user_id, user_info))

    user_question = reply_result.get('user_question', '')
    knowledge_solution_set = reply_result.get('knowledge_solution_set', '')
    wechat_skill_utter_set = reply_result.get('wechat_skill_utter_set', '')
    wechat_skill = reply_result.get('wechat_skill', '')
    wechat_skill_utter = reply_result.get('wechat_skill_utter', '')
    content = reply_result.get('reply_text', '').replace('\n', '').replace(' ', '')

    conversation_dict = {}
    conversation_dict["role"] = "assistant"
    conversation_dict["content"] = content
    query_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    conversation_dict["query_time"] = query_time
    conversation_dict["user_question"] = user_question
    conversation_dict["sales_skill_name"] = wechat_skill

    session_id_dict[user_id].append(conversation_dict)

    return json.dumps({
        'sessionId': user_id,
        'user_question': user_question,
        'knowledge_solution_set': knowledge_solution_set.replace('\n', '<br>'),
        'wechat_skill_utter_set': wechat_skill_utter_set.replace('\n', '<br>'),
        'wechat_skill_utter': wechat_skill_utter.replace('\n', '<br>'),
        'wechat_skill': wechat_skill.replace('\n', '<br>'),
        'context': content,
    })


if __name__ == '__main__':
    # config.load_config()
    app.run(host='0.0.0.0', port=8070)
